package com.deadline.statebutton;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.StateElement;
import ohos.app.Context;

public class StateImageView extends Image {
    private Element mNormalDrawable;

    private Element mPressedDrawable;

    private Element mUnableDrawable;

    private int mDuration = 0;

    private int[][] states;

    private StateElement mStateBackground;

    private StateImageView(Context context) {
        this(context, null);
    }

    private StateImageView(Context context, AttrSet attrSet) {
        this(context, attrSet, "0");
        context.getString(ResourceTable.String_app_name);
    }

    private StateImageView(Context context, AttrSet attrSet, String defStyleAttr) {
        super(context, attrSet, defStyleAttr);
        states = new int[4][];
        Element drawable = getBackgroundElement();
        if (drawable != null && drawable instanceof StateElement) {
            mStateBackground = (StateElement) drawable;
        } else {
            mStateBackground = new StateElement();
        }
        mNormalDrawable = attrSet.getAttr("normalBackground").get().getElement();
        mPressedDrawable = attrSet.getAttr("pressedBackground").get().getElement();
        mUnableDrawable = attrSet.getAttr("unableBackground").get().getElement();
        setStateBackground(mNormalDrawable, mPressedDrawable, mUnableDrawable);

        mDuration = attrSet.getAttr("").get().getIntegerValue();
        setAnimationDuration(mDuration);
    }

    /**
     * 设置不同状态下的背景
     * @param normal
     * @param pressed
     * @param unable
     */
    private void setStateBackground(Element normal, Element pressed, Element unable){
        this.mNormalDrawable = normal;
        this.mPressedDrawable = pressed;
        this.mUnableDrawable = unable;

        //set background
        if(mPressedDrawable != null) {
            mStateBackground.addState(states[0], mPressedDrawable);
            mStateBackground.addState(states[1], mPressedDrawable);
        }

        if(mUnableDrawable != null) {
            mStateBackground.addState(states[3], mUnableDrawable);
        }

        if(mNormalDrawable != null) {
            mStateBackground.addState(states[2], mNormalDrawable);
        }
        setBackground(mStateBackground);
    }

    /**
     * 设置动画时长
     *
     * @param duration
     *
     */
    private void setAnimationDuration(int duration) {
        this.mDuration = duration;
        mStateBackground.setEnterFadeDuration(mDuration);
        mStateBackground.setExitFadeDuration(mDuration);
    }
}
